package com.zwcl.payment.gateway.service.impl;

import com.zwcl.common.core.utils.SpringUtils;
import com.zwcl.payment.gateway.dto.PayParam;
import com.zwcl.payment.gateway.entity.PaymentLog;
import com.zwcl.payment.gateway.entity.PaymentMain;
import com.zwcl.payment.gateway.mq.producer.MqProducer;
import com.zwcl.payment.gateway.service.PaymentLogService;
import com.zwcl.payment.gateway.service.PaymentMainService;
import com.zwcl.payment.gateway.service.base.PayWayClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 专门处理小事务的过程
 */
@Service
@Slf4j
public class TransctionalServiceImpl {
    @Autowired
    PaymentMainService paymentMainService;

    @Autowired
    PaymentLogService paymentLogService;

    @Autowired
    private MqProducer mqProducer;

    @Transactional(rollbackFor = Exception.class)
    public String getPayInfo(PaymentMain payment, PayParam param){
        //新增支付流水
        if (payment == null) {
            payment = paymentMainService.savePaymentAndLog(param);     //该方法保持事务,方法内错误，会回滚
        } else {
            paymentLogService.addLog(new PaymentLog().setPaymentNo(payment.getPaymentNo()).setPayStatus(payment.getPayStatus()).setOperationInfo("{旧订单继续发起支付}"));
        }

        //发起扣费(上面方法抛出异常，则不会继续往下执行)
        PayWayClient client = SpringUtils.getBean("PayWayClient_" + param.getPayWay());
        String payInfo = client.pay(payment);

        //加入取消订单队列，9就是延时5分钟
        mqProducer.cancelOrder(payment.getPaymentNo(), 9);
        return payInfo;
    }
}

